package com.wanczy.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wanczy.pojo.Address;
import com.wanczy.pojo.Goods;
import com.wanczy.pojo.Order;
import com.wanczy.service.OrderService;
import com.wanczy.service.ShopService;

@Controller
public class OrderController {

	@Autowired
	private OrderService orderService;
	@Autowired
	private ShopService shopService;
	
	@ResponseBody
	@RequestMapping(value="/queryAddress")
	public List<Address> addCart(@RequestParam("userId") Integer userId) {
		List<Address> list = orderService.queryAddress(userId);
		return list;
	}
	
	@RequestMapping(value="/addOrder")
	public String addOrder(@RequestParam("userId") Integer userId,@RequestParam("goodsId") Integer goodsId,
			@RequestParam("cartNum") Integer cartNum,Map<String,Object> map) {
		Date date = new Date();
		Order order = new Order();
		order.setGoodsId(goodsId);
		order.setOrderNum(cartNum);
		order.setOrderTime(date);
		order.setUserId(userId);
		map.put("order", order);
		return "/order/Order";
	}	
	
	@ResponseBody
	@RequestMapping(value="/orderDetail")
	public List<Goods> orderDetail(@RequestParam("goodsId") Integer goodsId) {
		List<Goods> list = new ArrayList<>();
		Goods goods = shopService.findByGoodsId(goodsId);
		list.add(goods);
		return list;
	}
	
	@ResponseBody
	@RequestMapping(value="/buyGoods")
	public int buyGoods(Order order) {
		int count = 0;
		int result = 0;
		count = orderService.addOrder(order);
		if(count == 1) {
			count = orderService.desGoodsNum(order.getGoodsId(), order.getOrderNum());
			if(count == 1) {
				result = 2;//  2表示新增订单和减库存都成功
			}else {
				result = 3;//  3表示新增订单成功，减库存失败 
			}
		}
		return result;
	}
}
